<?php
namespace app\controllers;

use app\models\Blog;
use Phalcon\Mvc\Application\Exception;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Paginator\Adapter\QueryBuilder;

class BlogController extends BaseController
{
    public function indexAction()
    {
        $page = intval($this->request->get('page'));
        $query = $this->modelsManager->createBuilder()->from(Blog::class)->orderBy('id DESC')->columns('*');
        $paginator = new QueryBuilder([
            'builder' => $query,
            'limit' => 7,
            'page' => $page
        ]);
        $page = $paginator->getPaginate();
        $page = \Functions::getPagesByPage($page);
        $this->view->setVar('page', $page);
        return $this->view->render('blog', 'index');
    }

    public function createAction($id = 0)
    {
        $error = '';
        $id = intval($id);
        $title = '';
        $content = '';
        if ($id <=0) {
            $blog = new Blog();
        } else {
            $blog = Blog::findFirst([
                'id = ' . $id,
                'limit' => 1,
            ]);
            if  (!$blog) {
                throw new Exception('你请求的页面不存在');
            }
        }
        if($this->request->isPost()) {
            if ($this->security->checkToken()) {

                $blog->title = $this->request->getPost('title');
                $blog->content = $this->request->getPost('content');
                $blog->updated_at = time();
                $blog->created_at = time();
                $blog->author = $this->session->get('user')['id'];
                if ($blog->save()) {
                    return $this->response->redirect('/blog/index');
                }
                $error = $blog->getLastError();
            } else {
                $error = '你提交的数据无法验证';
            }
        }
        $title = $blog->title;
        $content = $blog->content;
        $this->view->setVars([
            'title' => $title,
            'content' => $content,
        ]);
        $this->view->setVar('error', $error);
        return $this->view->render('blog', 'form');
    }

    public function viewAction()
    {
        $id = intval($this->request->get('id'));
        $blog = Blog::findFirst(['id='.$id, 'limit' => 1]);
        if (!$blog) {
            throw new \Phalcon\Http\Request\Exception('你请求的页面不存在');
        }
        $this->view->setVar('title', $blog->title);
        $this->view->setVar('content', $blog->content);
        return $this->view->render('blog', 'view');
    }
}